<template>
  <div class="modalWrap">
    <div class="modalTitle">
      <span class="text">详情</span>
      <span class="close" @click="handleClose">x</span>
    </div>
    <div class="formWrap">
      <n-form
        ref="formRef"
        :model="taskForm"
        :rules="taskRules"
        :label-width="100"
        label-placement="left"
        require-mark-placement="right"
        :disabled="type === 'preview'"
      >
        <n-grid :cols="24" :x-gap="24">
          <template v-for="(item,index) in getFormOptions" :key="index">
            <n-form-item-gi :span="item.span" :label="item.label" :path="item.key" v-bind="item?.prop">
              <n-input v-if="item.type == 'input'" v-model:value="taskForm[item.key]" v-bind="item.props" :disabled="item.noEdit?.includes(type)" />
              <n-select v-if="item.type == 'select'" v-model:value="taskForm[item.key]" v-bind="item.props" :disabled="item.noEdit?.includes(type)" v-on="item.func" />
              <TaskStatus v-if="item.type === 't-step'" :data="taskForm" />
              <n-date-picker v-if="item.type == 'datetime'" v-model:formatted-value="taskForm[item.key]" v-bind="item.props" style="width: 100%;" />
            </n-form-item-gi>
          </template>
        </n-grid>
      </n-form>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '@/store/modules/user'
import { defineComponent, ref, unref, reactive, computed, toRefs, watch } from 'vue'
import { form, getSectionInfo, getAirInfo, getWayInfo, getNames, setNames } from '../tools/form.js'
// import FlyDetail from './FlyDetail.vue'
import { taskAdd, taskEdit, taskEditNew } from '@/api/task/index'
// import SlotPosition from './SlotPosition.vue'
import TaskStatus from './TaskStatus.vue'

export default defineComponent({
  name: 'TaskModal',
  components: { TaskStatus },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'create'
    },
    data: {
      type: Object,
      default: () => null
    },
    detail: {
      type: Object,
      default: () => null
    }
  },
  emits: {
    'update:visible': null,
    'reload': null
  },
  setup(props, { emit }) {
    const userStore = useUserStore()
    const { deptId } = userStore.userInfo

    const MODAL_TYPE = {
      'create': '新建任务',
      'preview': '任务详情',
      'update': '编辑任务'
    }

    // getRoadInfo() // 获取公路列表

    getAirInfo() // 机场列表
    if (props.data) {
      getSectionInfo(props.data.channelId, deptId)
      setNames(props.data)
      if (props.data.inspectionType === 2) {
        getWayInfo(props.data.airportId, deptId)
      }
    } else {
      getWayInfo()
    }

    const { formItem, taskForm, taskRules } = form
    const formRef = ref()
    // console.log(11111, props.detail.inspectionHistoryList?.[0].historyName)
    const data = reactive({
      loading: false,
      taskForm: {
        ...taskForm,
        ...props.data,
        legName: taskForm.legRange,
        failReason: props.detail.inspectionHistoryList?.[0].historyName
      },
      taskRules: {
        ...taskRules
      },
      backInfo: {
        channelId: unref(props.data?.channelId) || null,
        airportId: unref(props.data?.airportId) || null
      }
    })
    const getModalOptions = computed(() => {
      return {
        show: props.visible,
        title: MODAL_TYPE[props.type],
        loading: data.loading
        // negativeText: '取消',
        // positiveText: '确认'
      }
    })

    const getFormOptions = computed(() => {
      const list = formItem.filter((item) => {
        return !item.mode || item?.mode?.includes(data.taskForm.inspectionType)
      })
      return list
    })

    watch(() => [data.taskForm.channelId, data.taskForm.airportId], (val) => {
      const [channelId, airportId] = val
      if (data.backInfo.channelId !== channelId) {
        getSectionInfo(channelId, deptId)
        data.taskForm.legId = null
        data.backInfo.channelId = channelId
      }
      if (data.backInfo.airportId !== airportId) {
        const { droneId } = getNames()
        getWayInfo(droneId)
        data.taskForm.inspectionLine = null
        data.backInfo.airportId = airportId
      }
    })

    // 路线切换事件
    const roadChange = (e, obj) => {
      data.taskForm.inspectionLineName = obj.label
    }

    function handleConfirm(e) {
      if (props.type === 'preview') { handleClose(); return }
      formRef.value?.validate(async(errors) => {
        if (!errors) {
          data.loading = true
          const names = getNames()
          const params = {
            ...data.taskForm,
            ...names
          }
          if (params.inspectionType === 2) { // 机场
            params.isLive = null
            params.startLongitude = null
            params.startLatitude = null
            params.endLongitude = null
            params.endLatitude = null
          } else if (params.inspectionType === 3) { // 飞手
            params.airportId = null
            params.airportName = null
            params.inspectionLine = null
            params.inspectionLineName = null
          }
          if (props.type === 'update') {
            /* 重新提交 */
            taskEdit(params).then(res => {
              if (res.code === 0) {
                emit('reload')
                handleClose()
              }
              data.loading = false
            })
          } else if (props.type === 'create') {
            /* 新增 */
            taskAdd(params).then(res => {
              if (res.code === 0) {
                emit('reload')
                handleClose()
              }
              data.loading = false
            })
          } else if (props.type === 'edit') {
            /* 编辑 */
            taskEditNew(params).then(res => {
              if (res.code === 0) {
                emit('reload')
                handleClose()
              }
              data.loading = false
            })
          }
        } else {
          $message.error('请完善必填信息')
        }
      })
    }

    /* 关闭弹窗 */
    const handleClose = () => {
      emit('update:visible', false)
    }

    return {
      ...toRefs(data),
      formRef,
      getModalOptions,
      getFormOptions,
      handleConfirm,
      handleClose,
      roadChange
    }
  }
})
</script>

<style lang="scss" scoped>
.modalWrap{
  position: absolute;
  top: 12%;
  left: 20%;
  width: 849px;
  height: 569px;
  z-index: 9999;
  padding: 0 15px;
  box-sizing: border-box;
  background: url('./modal.png') no-repeat;
  .modalTitle{
    height: 45px;
    padding-left: 77px;
    margin-top: 15px;
    margin-bottom: 20px;
    border-bottom: 1px solid rgba(235,235,235,.3);
    .text {
      display: inline;
      font-size: 22px;
      color: #3B6BEC;
      font-family: DFPLiJinHeiW8-GB;
      font-weight: 400;
    }
    .text::after{
      content: '';
      display: block;
      position: absolute;
      top: 57px;
      left: 85px;
      height: 4px;
      width: 60px;
      background-color: #3B6BEC;
    }
    .close{
      color: #3B6BEC;
      position: absolute;
      right: 50px;
      font-size: 18px;
      font-weight: 700;
      top: 20px;
      cursor: pointer;
    }
  }
  .formWrap{
    box-sizing: border-box;
    padding: 0 40px;
  }
}
.n-input-number {
  width: 100%;
}
</style>
